package com.zuqiuzhandui.liveing.net;

import com.code19.library.DateUtils;
import com.code19.library.GsonUtil;
import com.code19.library.L;
import com.code19.library.NetUtils;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import com.zuqiuzhandui.liveing.common.MyApplication;
import com.zuqiuzhandui.liveing.model.evenbusModel.NoNetEven;
import com.zuqiuzhandui.liveing.model.resultModel.LiveCreateRs;
import com.zuqiuzhandui.liveing.model.resultModel.LiveNumberQtyRs;
import com.zuqiuzhandui.liveing.model.resultModel.LoginRs;
import com.zuqiuzhandui.liveing.model.resultModel.MemberRs;
import com.zuqiuzhandui.liveing.model.resultModel.TeamListRs;
import com.zuqiuzhandui.liveing.model.resultModel.TeamScheduleRs;

import org.greenrobot.eventbus.EventBus;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.functions.Func1;

import static com.zuqiuzhandui.liveing.myInterfacce.Constant.BASE_URL;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.DEFAULT_TIMEOUT;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.MEMBER_GET;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.MEMBER_MOBILE_LOGIN;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.SMS_SEND_CODE;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.TEAM_LIVE_CREATE;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.TEAM_LIVE_MEMBER_QTY;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.TEAM_LIVE_SEND_NOTIFY_TO_FANS;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.TEAM_MY_LIST;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.TEAM_MY_SCHEDULE_LIST;
import static com.zuqiuzhandui.liveing.myInterfacce.Constant.TOKEN_ERROR;

/**
 * Created by yq on 2016-10-10.
 */

public class HttpMethods {
    private Retrofit retrofit;
    private ZuqiuzhanduiApi httpService;

    private HttpMethods() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .addNetworkInterceptor(new StethoInterceptor())
                .addInterceptor(httpLoggingInterceptor);

        retrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
                .build();

        httpService = retrofit.create(ZuqiuzhanduiApi.class);
    }

    public static class singletionHolder {
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    public ZuqiuzhanduiApi getHttpService() {
        return httpService;
    }

    public static HttpMethods getInstance() {
        return singletionHolder.INSTANCE;
    }

    /**
     * @param url url地址
     * @param map 参数
     * @return 加密之后的url
     */
    private String getUrl(String url, Map<String, String> map) {
        L.d("sendPostMapIs:---------------------" + map);
        if (!NetUtils.isConnected(MyApplication.getInstance().getApplicationContext())) {
            L.d("sendPostMapIs:---------------------" + "发送无网络成功");
            EventBus.getDefault().post(new NoNetEven());
        }
        return new UrlFactory(url).setSecret(map).getUrl();
    }

    /**
     * 发送验证码
     *
     * @param subscriber
     * @param map
     */
    public void postSendCode(Subscriber<Integer> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestSendCode(getUrl(SMS_SEND_CODE, map), map)
            .map(new HttpResultFunc<Integer>()))
                .subscribe(subscriber);
    }

    /**
     * 登录
     *
     * @param subscriber
     * @param map
     */
    public void postLogin(Subscriber<LoginRs> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestLogin(getUrl(MEMBER_MOBILE_LOGIN, map), map)
                .map(new HttpResultFunc<LoginRs>())
                )
                .subscribe(subscriber);
    }

    /**
     * 获取用户信息
     *
     * @param subscriber
     * @param map
     */
    public void postMemberGet(Subscriber<MemberRs> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestMemberGet(getUrl(MEMBER_GET, map), map)
                .map(new HttpResultFunc<MemberRs>()))
                .subscribe(subscriber);
    }

    /**
     * 获取球队信息
     *
     * @param subscriber
     * @param map
     */
    public void postTeamListGet(Subscriber<List<TeamListRs>> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestTeamList(getUrl(TEAM_MY_LIST, map), map)
                .map(new HttpResultFunc<List<TeamListRs>>()))
                .subscribe(subscriber);
}

    /**
     * 获取球队的日程信息
     *
     * @param subscriber
     * @param map
     */
    public void postTeamScheduleGet(Subscriber<List<TeamScheduleRs>> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestTeamSchedule(getUrl(TEAM_MY_SCHEDULE_LIST, map), map)
                .map(new HttpResultFunc<List<TeamScheduleRs>>()))
                .subscribe(subscriber);
    }

    /**
     * 获取直播信息(推流信息和播放地址)
     *
     * @param subscriber
     * @param map
     */
    public void postLiveCreate(Subscriber<LiveCreateRs> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestLiveCreate(getUrl(TEAM_LIVE_CREATE, map), map)
                .map(new HttpResultFunc<LiveCreateRs>()))
                .subscribe(subscriber);
    }


    /**
     * 获取观看人数(推流信息和播放地址)
     *
     * @param subscriber
     * @param map
     */
    public void postLiveNumberQty(Subscriber<LiveNumberQtyRs> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestLiveNubberQty(getUrl(TEAM_LIVE_MEMBER_QTY, map), map)
                .map(new HttpResultFunc<LiveNumberQtyRs>()))
                .subscribe(subscriber);
    }


    /**
     * 通知粉丝
     *
     * @param subscriber
     * @param map
     */
    public void postNotify(Subscriber<Integer> subscriber, Map<String, String> map) {
        ObservableDecorator.decorate(httpService.requestNotify(getUrl(TEAM_LIVE_SEND_NOTIFY_TO_FANS, map), map)
                .map(new HttpResultFunc<Integer>()))
                .subscribe(subscriber);
    }



    private class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {

        @Override
        public T call(HttpResult<T> httpResult) {
            if (httpResult.getErrorCode()==206||httpResult.getErrorCode()==207){
                throw new ApiException(TOKEN_ERROR);
            }
           else if (httpResult.getErrorCode() != 0) {
                throw new ApiException(httpResult.getMsg());
            }
            return httpResult.getData();
        }
    }


}
